package com.ldl.origami.controller.index;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.ldl.origami.common.ErrorModelAndView;
import com.ldl.origami.domain.*;
import com.ldl.origami.origamiService.*;
import com.ldl.origami.util.Constants;
import com.ldl.origami.util.InitServlet;
import com.ldl.origami.util.TutorialToJson;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.DecimalFormat;
import java.util.List;

/**
 * 功能描述:
 * 作者: LDL
 * 创建时间: 2014/7/16 21:08
 */
@Controller
public class IndexController {

    static Logger logger = LoggerFactory.getLogger(IndexController.class);
    @Autowired(required = false)
    private IndexService indexService;

    @Autowired(required = false)
    private TutorialService tutorialService;

    @Autowired(required = false)
    private UserService userService;

    @Autowired(required = false)
    private UserScoreService userScoreService;

    @Autowired(required = false)
    private TutorialStoreService tutorialStoreService;

    @Autowired(required = false)
    private CategoryService categoryService;
    /**
     * 访问主页
     * @param request
     * @return
     */
    @RequestMapping("/index")
    public ModelAndView index(HttpServletRequest request) {

        HttpSession session = request.getSession();
        List<Tutorial> tutorials = indexService.getAllTutorialsWithThroughTheAudit();
        ModelAndView modelAndView = new ModelAndView();
        String userName = (String) session.getAttribute(Constants.SESSION_USERNAME);
        User user = null;
        List<TutorialStore> tutorialStores = null;
        if(userName != null){
            try {
                user = userService.getUserByUserName(userName);
                tutorialStores = tutorialStoreService.getTutorialStoreByUser(userName);
            } catch (Exception e) {
                return new ErrorModelAndView(user);
            }
        }
        if(tutorials.size() == 0){
            tutorials = null;
        }else{
            if(tutorialStores != null && tutorialStores.size()>0){
                for(int i=0;i<tutorials.size();i++){
                    Tutorial tutorial = tutorials.get(i);
                    for(int j=0;j<tutorialStores.size();j++){
                        if(tutorial.getId() == tutorialStores.get(j).getTutorialid()){
                            tutorial.setStored(true);
                            break;
                        }
                    }
                }
            }
        }
        modelAndView.addObject("tutorials", tutorials);
        modelAndView.addObject("user",user);
        modelAndView.setViewName("index");
        return modelAndView;
    }

    /**
     * 查看教程内容
     * @param request
     * @return
     */
    @RequestMapping("/viewTheContents")
    public ModelAndView viewTheContents(HttpServletRequest request){

        HttpSession session = request.getSession();
        int tutorialId = Integer.parseInt(request.getParameter("id"));
        String userName = (String) session.getAttribute(Constants.SESSION_USERNAME);
        TutorialData tutorialData = new TutorialData();
        User user = null;
        if (userName != null) {
            try {
                user = userService.getUserByUserName(userName);
            } catch (Exception e) {
                return new ErrorModelAndView(user);
            }
        }
        Tutorial tutorial = null;
        try {
            tutorial = tutorialService.getTutorialById(tutorialId);
        } catch (Exception e) {
            return new ErrorModelAndView(user);
        }

        tutorialData.setTutorial(tutorial);
        List<UserScore> userScores = null;

        try{
            userScores = userScoreService.getUserScore(userName,tutorialId);
        }catch (Exception e){
            return new ErrorModelAndView(user);
        }

        if(userScores != null && userScores.size()>0){
            tutorialData.setRatingByUser(true);
            tutorialData.setUserScore(userScores.get(0));
        }

        //非本人访问浏览量+1(只计算登录用户)
        if(user != null && !userName.equals(tutorial.getUserName())){

            Tutorial tutorialWithNewViews = new Tutorial();
            tutorialWithNewViews.setId(tutorialId);
            tutorialWithNewViews.setViews(tutorial.getViews()+1);
            try {
                tutorialService.updateViews(tutorialWithNewViews);
            } catch (Exception e) {
                return new ErrorModelAndView(user);
            }
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("tutorialData", tutorialData);
        modelAndView.addObject("user", user);
        modelAndView.setViewName("tutorial/viewTheContents");
        return modelAndView;
    }


    /**
     * 404错误
     * @param request
     * @return
     */
    @RequestMapping("/404error")
    public ModelAndView error(HttpServletRequest request){
        HttpSession session = request.getSession();
        String userName = (String) session.getAttribute(Constants.SESSION_USERNAME);
        User user = null;
        if (userName != null) {
            try {
                user = userService.getUserByUserName(userName);
            } catch (Exception e) {
                return new ErrorModelAndView(user);
            }
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user", user);
        modelAndView.setViewName("error/404error");
        return modelAndView;
    }

    /**
     * 工具栏
     * @param request
     * @return
     */
    @RequestMapping("/topNav")
    public String topNav(HttpServletRequest request) {
        return "topNav";
    }


    /**
     * 收藏教程
     * @param request
     * @return
     */

    @RequestMapping("/stored")
    @ResponseBody
    public String stored(HttpServletRequest request){

        HttpSession session = request.getSession();
        String userName = (String) session.getAttribute(Constants.SESSION_USERNAME);
        int tutorialId = Integer.parseInt(request.getParameter("tutorialId"));

        TutorialStore tutorialStore = new TutorialStore();
        tutorialStore.setUsername(userName);
        tutorialStore.setTutorialid(tutorialId);
        DateTime dateTime = DateTime.now();
        tutorialStore.setStoretime(dateTime.toDate());

        Tutorial tutorial = null;
        try{
            tutorial = tutorialService.getTutorialById(tutorialId);
        } catch (Exception e) {
            return "error";
        }

        Tutorial tutorialUpdate = new Tutorial();
        tutorialUpdate.setId(tutorialId);
        tutorialUpdate.setStores(tutorial.getStores()+1);

        try {
            tutorialStoreService.stored(tutorialStore, tutorialUpdate);
        } catch (Exception e) {
            return "error";
        }

        return "success";

    }


    /**
     * 取消收藏教程
     * @param request
     * @return
     */

    @RequestMapping("/unStored")
    @ResponseBody
    public String unStored(HttpServletRequest request){

        HttpSession session = request.getSession();
        String userName = (String) session.getAttribute(Constants.SESSION_USERNAME);
        int tutorialId = Integer.parseInt(request.getParameter("tutorialId"));

        Tutorial tutorial = null;
        try {
            tutorial = tutorialService.getTutorialById(tutorialId);
        } catch (Exception e) {
            return "error";
        }

        Tutorial tutorialUpdate = new Tutorial();
        tutorialUpdate.setId(tutorialId);
        tutorialUpdate.setStores(tutorial.getStores() - 1);

        try {
            tutorialStoreService.unStored(userName, tutorialId, tutorialUpdate);
        } catch (Exception e) {
            return "error";
        }

        return "success";

    }


    /**
     * 我的收藏
     * @param request
     * @return
     */
    @RequestMapping("/myCollection")
    public ModelAndView myCollection(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String userName = (String) session.getAttribute(Constants.SESSION_USERNAME);

        TutorialStorePage tutorialStorePage = new TutorialStorePage();
        tutorialStorePage.setUserName(userName);
        tutorialStorePage.setBegin(0);
        tutorialStorePage.setEnd(InitServlet.myCollectionLimit);

        TutorialData tutorialData = new TutorialData();

        User user = null;
        List<Integer> myCollectionsId;
        List<Tutorial> myCollections = null;

        if (userName != null) {
            try {
                user = userService.getUserByUserName(userName);
                myCollectionsId = tutorialStoreService.getMyCollectionsIdByPage(tutorialStorePage);
                if(myCollectionsId.size()>0){
                    myCollections = tutorialService.getMyCollections(myCollectionsId);
                }
            } catch (Exception e) {
                return new ErrorModelAndView(user);
            }
        }

        tutorialData.setMyCollections(myCollections);

        if (myCollections != null && myCollections.size() < InitServlet.myCollectionLimit) {
            tutorialData.setMycollections_requires_pagination(false);
        }

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user", user);
        modelAndView.addObject("tutorialData", tutorialData);
        modelAndView.setViewName("tutorial/myCollection");
        return modelAndView;
    }


    /**
     * 读取更多我的收藏
     *
     * @param request
     * @return
     */
    @RequestMapping("/showMoreCollections")
    @ResponseBody
    public TutorialData showMoreCollections(HttpServletRequest request) {

        HttpSession session = request.getSession();
        String userName = (String) session.getAttribute(Constants.SESSION_USERNAME);

        int page = Integer.parseInt(request.getParameter("page"));

        PageBounds pageBounds = new PageBounds(page,InitServlet.myCollectionLimit);

        TutorialStorePage tutorialStorePage = new TutorialStorePage();
        tutorialStorePage.setUserName(userName);
        tutorialStorePage.setBegin(pageBounds.getOffset());
        tutorialStorePage.setEnd(pageBounds.getLimit());

        TutorialData tutorialData = new TutorialData();

        List<Integer> myCollectionIds = null;
        List<Tutorial> myCollections = null;
        try {
            myCollectionIds = tutorialStoreService.getMoreMyCollectionsIdByPage(tutorialStorePage);
            if(myCollectionIds.size()>0){
                myCollections = tutorialService.getMyCollections(myCollectionIds);
            }
            } catch (Exception e) {
        }

        tutorialData.setMyCollections(myCollections);

        if ((myCollections != null && myCollections.size() < InitServlet.myCollectionLimit)) {
            tutorialData.setMycollections_requires_pagination(false);
        }
        return tutorialData;
    }


    /**
     * 我的教程
     *
     * @param request
     * @return
     */
    @RequestMapping("/myTutorials")
    public ModelAndView myTutorials(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String userName = (String) session.getAttribute(Constants.SESSION_USERNAME);

        TutorialPage tutorialPage = new TutorialPage();
        tutorialPage.setUserName(userName);
        tutorialPage.setBegin(0);
        tutorialPage.setEnd(InitServlet.myTutorialsLimit);

        TutorialData tutorialData = new TutorialData();

        User user = null;
        List<Tutorial> myTutorials = null;

        if (userName != null) {
            try {
                user = userService.getUserByUserName(userName);
                myTutorials = tutorialService.getMyTutorials(tutorialPage);
            } catch (Exception e) {
                return new ErrorModelAndView(user);
            }
        }

        if(myTutorials != null){

            if(myTutorials.size()>0){

                for (int i = 0; i < myTutorials.size(); i++) {
                    Tutorial tutorial = myTutorials.get(i);
                    if (tutorial.getAuditing().equals("N")) {
                        tutorial.setAudited(false);
                    }
                }

                if (myTutorials.size() < InitServlet.myTutorialsLimit) {
                    tutorialData.setMytutorialss_requires_pagination(false);
                }

            }else{
                myTutorials = null;
            }

        }

        tutorialData.setMyTutorials(myTutorials);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user", user);
        modelAndView.addObject("tutorialData", tutorialData);
        modelAndView.setViewName("tutorial/myTutorials");
        return modelAndView;
    }


    /**
     * 读取更多我的教程
     *
     * @param request
     * @return
     */
    @RequestMapping("/showMoreMyTutorials")
    @ResponseBody
    public TutorialToJson showMoreMyTutorials(HttpServletRequest request) {

        HttpSession session = request.getSession();
        String userName = (String) session.getAttribute(Constants.SESSION_USERNAME);

        int page = Integer.parseInt(request.getParameter("page"));

        PageBounds pageBounds = new PageBounds(page, InitServlet.myTutorialsLimit);

        TutorialPage tutorialPage = new TutorialPage();
        tutorialPage.setUserName(userName);
        tutorialPage.setBegin(pageBounds.getOffset());
        tutorialPage.setEnd(pageBounds.getLimit());

        TutorialToJson tutorialToJson = new TutorialToJson();

        List<Tutorial> myTutorials = null;

        try {
            myTutorials = tutorialService.getMyTutorials(tutorialPage);
        } catch (Exception e) {
        }

        if (myTutorials != null) {

            if (myTutorials.size() > 0) {

                DecimalFormat df = new DecimalFormat("0.0");
                StringBuffer stringBuffer = new StringBuffer();
                for (int i = 0; i < myTutorials.size(); i++) {
                    Tutorial tutorial = myTutorials.get(i);
                    DateTime dateTime = new DateTime(tutorial.getCreateTime());
                    stringBuffer.append("<div class='media' id='" + tutorial.getId() + "_all'>")
                            .append("<img class = 'media-object pull-left' src = '" + tutorial.getTitleImgPath() + "' width = '128' " +
                                    "length = '128' style = 'margin-top:15px'>")
                            .append("<div class = 'media-body'><p  style = 'color: #999999;margin-bottom: 3px;margin-left: 5px;' >" +
                                    tutorial.getUserName() + "&nbsp;&nbsp;&nbsp;")
                            .append(dateTime.toString("YYYY-MM-dd HH:mm:ss")+"&nbsp;&nbsp;&nbsp;"+tutorial.getScorecount()+"人评分 &nbsp;<font color = 'green' size = '5'>");
                            if(tutorial.getScorecount() > 0){
                                stringBuffer.append(df.format(tutorial.getTotalscore()/ tutorial.getScorecount()));
                            }else{
                                stringBuffer.append("0.0");
                            }
                    stringBuffer.append("</font>分&nbsp;&nbsp;");

                    if (tutorial.getAuditing().equals("N")) {
                        stringBuffer.append("<font style='color: #ff0000'>审核中</font>");
                    }
                    stringBuffer.append("</p><h4 class = 'media-heading'>" +
                            "<a href = 'javascript:show(" + tutorial.getId() + ")'>"+tutorial.getTitle()+"</a></h4>")
                            .append("<div class = 'caption' style = 'margin-left: 5px' ><p>"+tutorial.getIntroduce()+"</p><p style = 'color: " +
                                    "#999999'>")
                            .append("<span class = 'glyphicon glyphicon-eye-open'></span>&nbsp;"+tutorial.getViews()+"次浏览&nbsp;&nbsp;")
                            .append("<span class ='glyphicon glyphicon-comment'></span>&nbsp;0条评论&nbsp;&nbsp;")
                            .append("<span class = 'glyphicon glyphicon-star'></span>&nbsp;" + tutorial.getStores() + "人收藏&nbsp;&nbsp;")
                            .append("<span class = 'glyphicon glyphicon-edit'></span>&nbsp;<a href='javascript:edit(" +tutorial.getId()+")'" +
                                    "style='color:#999999'>编辑</a>&nbsp;&nbsp;")
                            .append("<span class = 'glyphicon glyphicon-remove'></span>&nbsp;<a href='javascript:deleteTutorial(" +
                                    tutorial.getId()
                                    +")' style='color:#999999'>删除</a></p></div></div></div>");
                }

                tutorialToJson.setJsonString(stringBuffer.toString());

                if (myTutorials.size() < InitServlet.myTutorialsLimit) {
                    tutorialToJson.setRequires_pagination(false);
                }




            } else {
                tutorialToJson.setStatus("empty");
            }

        }else{
            tutorialToJson.setStatus("empty");
        }




        return tutorialToJson;
    }

    /**
     * 删除教程
     *
     * @param request
     * @return
     */

    @RequestMapping("/deleteTutorial")
    @ResponseBody
    public String deleteTutorial(HttpServletRequest request) {

        HttpSession session = request.getSession();
        String userName = (String) session.getAttribute(Constants.SESSION_USERNAME);

        int tutorialId = Integer.parseInt(request.getParameter("tutorialId"));

        try {
            tutorialService.deleteTutorialById(tutorialId);
        } catch (Exception e) {
            return "error";
        }

        return "success";

    }

    /**
     * 编辑教程
     *
     * @param request
     * @return
     */

    @RequestMapping("/editTutorial")
    public ModelAndView editTutorial(HttpServletRequest request) {

        HttpSession session = request.getSession();
        String userName = (String) session.getAttribute(Constants.SESSION_USERNAME);

        int tutorialId = Integer.parseInt(request.getParameter("tid"));

        User user = null;
        if (userName != null) {
            try {
                user = userService.getUserByUserName(userName);
            } catch (Exception e) {
                return new ErrorModelAndView(user);
            }
        }

        Tutorial tutorial = null;

        try {
            tutorial = tutorialService.getTutorialById(tutorialId);
        } catch (Exception e) {
            return new ErrorModelAndView(user);
        }


        Category category = null;
        try{
            category = categoryService.getCategoryById(tutorial.getCategory());
        } catch (Exception e) {
            return  new ErrorModelAndView(user);
        }

        List<Category> categories = categoryService.getCategories();

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user", user);
        modelAndView.addObject("tutorial", tutorial);
        modelAndView.addObject("category", category);
        modelAndView.addObject("categories", categories);
        modelAndView.setViewName("tutorial/editTutorial");

        return modelAndView;

    }
}
